import re

from django_redis import get_redis_connection
from redis import RedisError
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from goods.models import SKU
from utils.exceptions import logger
from .models import User, Address


class RegisterSmsCodeSerializer(serializers.Serializer):

    text = serializers.CharField(max_length=4, min_length=4, required=True, label='图形验证码')

    image_code_id = serializers.UUIDField(required=True, label="UUID")

    """
    序列化器验证的四种方式
    1 类型验证
    2 选项验证
    3 单个字段
    4 多个字段
    """

    def validate(self, attrs):
        # 获取用户输入的
        text = attrs.get("text")
        image_code_id = attrs.get("image_code_id")
        # 获取redis的验证码
        redis_conn = get_redis_connection("code")
        redis_text = redis_conn.get('img_%s' % image_code_id)
        # 判断redis中的验证码是否存在
        if redis_text is None:
            raise serializers.ValidationError('验证码已过期')
        # 将redis中的图片验证码删除
        try:
            redis_conn.delete('img_%s' % image_code_id)
        except RedisError as e:
            logger.error(e)
        # 比较二者
        # redis的数据是bytes类型 用户不管大小写
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError('验证码错误')
        return attrs



class RegisterCreateSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')  # 增加token
        # 注意我们自己添加的字段,也是需要添加到field中的
        extra_kwargs = {
            'id':{'read_only':True},
            'username':{
                'min_length':5,
                'max_length':20,
                'error_messages':{
                    'min_length':'仅允许5-20个字符的用户名',
                    'max_length':'仅允许5-20个字符的用户名',
                }
            },
            'password':{
                'write_only':True,
                'min_length':8,
                'max_length':20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的用户名',
                    'max_length': '仅允许8-20个字符的用户名',
                }
            }
        }

    def validate_mobile(self, attrs):
        if not re.match(r'1[345789]\d{9}', attrs):
            raise serializers.ValidationError('手机号格式不正确')
        return attrs

    def validate_allow(self, attrs):
        if attrs != 'true':
            raise serializers.ValidationError('您未同意协议')
        return attrs
    def validate(self, attrs):
        password = attrs['password']
        password2 = attrs['password2']
        if password != password2:
            raise serializers.ValidationError('密码不一致')
        code = attrs['sms_code']
        redis_conn = get_redis_connection('code')
        mobile = attrs['mobile']
        redis_code = redis_conn.get('sms_%s' % mobile).decode()
        if redis_code is None:
            raise serializers.ValidationError('验证码过期')
        if redis_code != code:
            raise serializers.ValidationError('验证码不正确')
        return attrs

    def create(self, validated_data):

        # 删除多余字段
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)
        user.set_password(validated_data['password'])
        # 注册完成
        user.save()
        # 补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user


class UserCentetInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id','username','email','mobile','email_active']


class EmailSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['email']


class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def create(self, validated_data):
        #Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title')


class UserHistroySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(label='商品id',required=True,min_value=1)

    def validate_sku_id(self, value):
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    def create(self, validated_data):

        # 获取用户信息
        user_id = self.context['request'].user.id
        # 获取商品id
        sku_id = validated_data['sku_id']
        # 连接redis
        redis_conn = get_redis_connection('history')
        # 移除已经存在的本记录
        redis_conn.lrem('history_%s' % user_id, 0, sku_id)
        # 添加新的记录
        redis_conn.lpush('history_%s' % user_id, sku_id)
        # 保存最多5条记录
        redis_conn.ltrim('history_%s' % user_id, 0, 4)
        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ('id', 'name', 'price', 'default_image_url', 'comments')